package com.SweetWhite.UserManagement.model.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.SweetWhite.UserManagement.model.bean.Hero_User;
import com.SweetWhite.UserManagement.model.service.SelectService;




@Controller
public class LoginController extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
	private SelectService service;
	@RequestMapping("check.action")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		req.setCharacterEncoding("UTF-8");
//		resp.setCharacterEncoding("UTF-8");
		String username=req.getParameter("username");
		PrintWriter pw=resp.getWriter();
		try {
			Hero_User hu=service.getHero_UserByName(username);
			if(hu.getRealName().equals(username)) {
				pw.print("用户存在，把密码也填好吧……");
			}
		} catch (Exception e) {
			// TODO: handle exception
				pw.print("查无此人");
		}finally {
			pw.flush();
			pw.close();
		}
	}
	@RequestMapping("login.action")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		String password=req.getParameter("password");
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter pw=resp.getWriter();
		try {
			Hero_User hu=service.getHero_UserByName(req.getParameter("username"));
			if(hu.getPassword().equals(password)) {
				HttpSession session=req.getSession();
				session.setAttribute("user", hu);
				resp.sendRedirect("main.jsp");
			}else {
				pw.print("<script>alert('密码错误……再好好想想吧');history.back();</script>");
			}
		} catch (Exception e) {
			// TODO: handle exception
			pw.print("<script>alert('你把名字写对了吗？');history.back();</script>");
		}finally {
			pw.flush();
			pw.close();
		}
	}
}
